package cn.myjerry.test.JDBC;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 测试事务的基本概念和用法
 * @author Jerry
 *
 */
public class Demo05 {
	// JDBC 驱动名及数据库 URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
    static final String DB_URL = "jdbc:mysql://localhost:3306/testjdbc?useSSL=true&useUnicode=true&characterEncoding=utf8";
    
    // 数据库的用户名与密码，需要根据自己的设置
    static final String USER = "root";
    static final String PASS = "Jerry1912317";
	
	public static void main(String[] args) {
		Connection conn = null;
		PreparedStatement ps1 = null;
		PreparedStatement ps2 = null;
		// 加载驱动类
		try {
			Class.forName(JDBC_DRIVER);
			conn = DriverManager.getConnection(DB_URL, USER, PASS);
			
			conn.setAutoCommit(false);	// JDBC 默认自动提交事务
			
			ps1 = conn.prepareStatement("INSERT INTO User (Name,PassWord) VALUES (?,?)");
			ps1.setString(1, "Jerry");
			ps1.setString(2, "123456");
			ps1.execute();
			
			Thread.sleep(6000);
			
			ps2 = conn.prepareStatement("INSERT INTO User (Name,PassWord) VALUES (?,?,?)");
			ps2.setString(1, "Tom");
			ps2.setString(2, "123456");
			ps2.execute();
			
			conn.commit();
			
		} catch (Exception e) {
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		} finally {
			if(ps1 != null) {
				try {
					ps1.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(ps2 != null) {
				try {
					ps2.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
